//
//  UIImageView+BCWebImage.m
//  BCWebImageKit
//
//  Created by Basic on 2018/5/24.
//  UIImageView web图片加载扩展

#import "UIImageView+BCWebImage.h"
#import <BCFoundation/BCFoundationUtils.h>
#import <BCFoundation/NSURL+BCHelper.h>
#import <BCFoundation/UIImage+BCHelper.h>
#import <objc/runtime.h>

// SDWEBIMAGE_INNER，表示是否使用内嵌的sdwebimage，在podspec里定义
#ifdef SDWEBIMAGE_INNER
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#else
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/SDImageCache.h>
#pragma clang diagnostic pop
#endif


@implementation UIImageView (BCWebImage)

//MARK: - property
-(UIColor *)bc_placeholderColor {
    return objc_getAssociatedObject(self, @selector(bc_placeholderColor));
}
-(void)setBc_placeholderColor:(UIColor *)bc_placeholderColor {
    objc_setAssociatedObject(self, @selector(bc_placeholderColor), bc_placeholderColor, OBJC_ASSOCIATION_RETAIN);
}
-(UIViewContentMode )bc_placeholderContentMode {
    return [objc_getAssociatedObject(self, @selector(bc_placeholderContentMode)) integerValue];
}
-(void)setBc_placeholderContentMode:(UIViewContentMode)bc_placeholderContentMode {
    objc_setAssociatedObject(self, @selector(bc_placeholderContentMode), @(bc_placeholderContentMode), OBJC_ASSOCIATION_ASSIGN);
}
-(UIColor *)bc_originColor {
    return objc_getAssociatedObject(self, @selector(bc_originColor));
}
-(void)setBc_originColor:(UIColor *)bc_originColor {
    objc_setAssociatedObject(self, @selector(bc_originColor), bc_originColor, OBJC_ASSOCIATION_RETAIN);
}
-(NSNumber *)bc_originContentMode {
    return objc_getAssociatedObject(self, @selector(bc_originContentMode));
}
-(void)setBc_originContentMode:(NSNumber *)bc_originContentMode {
    objc_setAssociatedObject(self, @selector(bc_originContentMode), bc_originContentMode, OBJC_ASSOCIATION_RETAIN);
}

//MARK: - 设置图片
- (void)bc_setImageWithURL:(NSString *)imageStr placeHolderImage:(UIImage *)placeHolderImage {
    [self bc_setImageWithURL:imageStr placeholderImage:placeHolderImage complete:nil];
}
- (void)bc_setSameWidthImageWithURL:(NSString *)imageStr placeHolderImage:(UIImage *)placeHolderImage {
    NSString *imageURL = imageStr;
    NSString *widthStr = nil;
    if(self.constraints.count > 0 ){
        //根据 width constraint 下载图片
        for (NSLayoutConstraint *constraint in self.constraints) {
            if (constraint.firstItem == self && constraint.firstAttribute == NSLayoutAttributeWidth && constraint.constant > 0) {
                widthStr = [NSString stringWithFormat:@"%d",((int)constraint.constant * (int)UIScreen.mainScreen.scale)];
                break;
            }
        }
    }
    if (widthStr == nil && self.frame.size.width > 0) {
        //根据 frame 下载图片
        widthStr = [NSString stringWithFormat:@"%d",((int)self.frame.size.width * (int)UIScreen.mainScreen.scale)];
    }
    if (widthStr != nil) {
        imageURL = kBCImgWidthURL(imageURL, widthStr);
    }
    [self bc_setImageWithURL:imageURL placeholderImage:placeHolderImage complete:nil];
}
- (void)bc_setImageWithURL:(NSString * _Nullable)imageURL withScaleWidth:(CGFloat )scaleWidth withPlaceHolderImage:(UIImage * _Nullable)placeHolderImage {
    NSString *widthStr = [NSString stringWithFormat:@"%d",((int)scaleWidth * (int)UIScreen.mainScreen.scale)];
    [self bc_setImageWithURL:kBCImgWidthURL(imageURL, widthStr) placeholderImage:placeHolderImage complete:nil];
}
- (void)bc_setImageWithURL:(NSString *)imageStr width:(NSString *)widthStr placeHolderImage:(UIImage *)placeHolderImage {
    imageStr = kBCImgWidthURL(imageStr, widthStr);
    [self bc_setImageWithURL:imageStr placeholderImage:placeHolderImage complete:nil];
}
- (void)bc_setImageWithURL:(NSString *)imageStr placeholderImage:(UIImage *)placeholderImage complete:(void(^)(BOOL success, UIImage *image, UIImageView *imageView) )complete {
    //原始的背景色
    UIColor *orginalBgColor = [self bc_originColor];
    if (!orginalBgColor) {
        orginalBgColor = self.backgroundColor;
    }
    //原始的内容模式
    NSNumber *orginalContentMode = [self bc_originContentMode];
    if (!orginalContentMode) {
        orginalContentMode = @(self.contentMode);
    }
    //有预览图
    if (placeholderImage) {
        if (self.bc_placeholderColor) {
            //保存原来背景色
            [self setBc_originColor:orginalBgColor];
            self.backgroundColor = self.bc_placeholderColor;
            //保存原来的内容模式
            [self setBc_originContentMode:orginalContentMode];
            self.contentMode = self.bc_placeholderContentMode;
        }
    }
    // 兼容url特殊符号URLWithString返回nil处理
    NSURL *imgURL = [NSURL bc_URLWithString:imageStr];
    @BCWeakify(self);
    [self sd_setImageWithURL:imgURL placeholderImage:placeholderImage completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        @BCStrongify(self);
        if (image) {
            //下载成功，恢复背景色和内容模式
            self.backgroundColor = orginalBgColor;
            if (orginalContentMode) {
                self.contentMode = [orginalContentMode integerValue];
            }
        }
        if (complete != nil) {
            complete((error ==nil), image, self);
        }
    }];
}

- (void)bc_setImageWithURL:(NSString * _Nullable)imageStr radius:(CGFloat)radius placeHolderImage:(UIImage * _Nullable)placeHolderImage {

    UIColor *orginalBgColor = self.backgroundColor;//原始的背景色
    NSNumber *orginalContentMode = nil;//原始的内容模式
    //有预览图
    if (placeHolderImage) {
        if (self.bc_placeholderColor) {
            self.backgroundColor = self.bc_placeholderColor;
        }
        if (self.bc_placeholderContentMode != self.contentMode) {
            orginalContentMode = @(self.contentMode);//保存原来的内容模式
            self.contentMode = self.bc_placeholderContentMode;
        }
    }
    // 兼容url特殊符号URLWithString返回nil处理
    NSURL *imgURL = [NSURL bc_URLWithString:imageStr];
    @BCWeakify(self);
    void(^imageBlock)(UIImage *image) = ^(UIImage *image){
        @BCStrongify(self);
        if (image) {
            self.image = image;
            //下载成功，恢复背景色和内容模式
            self.backgroundColor = orginalBgColor;
            if (orginalContentMode) {
                self.contentMode = [orginalContentMode integerValue];
            }
        }
    };
    NSString *cacheKey = [[SDWebImageManager sharedManager] cacheKeyForURL:imgURL];
    UIImage *cacheImg = [[SDImageCache sharedImageCache] imageFromCacheForKey:cacheKey];
    if (cacheImg) {
        imageBlock(cacheImg);
    }else{
        [self sd_setImageWithURL:imgURL placeholderImage:placeHolderImage completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (image) {
                UIImage *radiusImg = [image bc_imageWithCornerRadius:radius];
                imageBlock(radiusImg);
                [[SDImageCache sharedImageCache] storeImage:radiusImg forKey:imgURL completion:NULL];
            }
        }];
    }
}
@end
